package com.systop.cardecorate.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.systop.cardecorate.admin.entity.AdminEntity;
import com.systop.cardecorate.admin.entity.LoginForm;
import com.systop.cardecorate.admin.service.AdminService;
import com.systop.cardecorate.admin.service.CaptchaService;
import com.systop.common.exception.BizCodeEnum;
import com.systop.common.utils.PageCheck;
import com.systop.common.utils.PageUtils;
import com.systop.common.utils.R;
import com.systop.common.validator.group.AddGroup;
import com.systop.common.validator.group.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Map;


/**
 * 
 *
 * @author jsj
 * @email jsj@gmail.com
 * @date 2022-05-05 11:46:06
 */
@Slf4j
@RestController
@RequestMapping("payment/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private CaptchaService captchaService;

    /**
     * 列表
     */

    @RequestMapping(value = "/list")
    @Operation(summary = "查询所有用户")
    //@RequiresPermissions("payment:admin:list")
    public R list(
            @Parameter(description="params包含page和limit,默认为page为1,limit为10",
                    allowEmptyValue = true)
            @RequestParam Map<String, Object> params){
        // System.out.println(params);
        //查询数据
        PageUtils page = adminService.queryPage(params);

        Map<String, Object> resultMap = PageCheck.pageCheck(params, page);

        if(!resultMap.get("page").equals(page.getCurrPage())){
            //当前页与上次访问页不同
            page = adminService.queryPage(resultMap);
        }

        if(page.getCurrPage()>1&&page.getList().size()==0){
            return R.error(BizCodeEnum.INVALID_QUERY.getCode(),BizCodeEnum.INVALID_QUERY.getMsg());
        }

        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @Operation(summary ="根据id查询用户")
            //@RequiresPermissions("payment:admin:info")
    public R info(@PathVariable("id") Integer id){
		AdminEntity admin = adminService.getById(id);
        return R.ok().put("admin", admin);
    }

    @PostMapping("/login")
    @Operation(summary = "登录方法")
    public R findUser(@Validated @RequestBody Map<String,Object> map){
        // System.out.println(System.currentTimeMillis());
        // System.out.println(map);

        //将JSON数据转换成java能识别的对象类数据
        LoginForm form =
                JSON.parseObject(JSON.parse(JSON.toJSONString(map.get("loginForm"))).toString(),
                        new TypeReference<LoginForm>(){});
        // System.out.println(form);

        //验证验证码是否正确
        boolean captcha = captchaService.validate(form.getUuid(), form.getCaptcha());
        if(!captcha){
            return R.error(BizCodeEnum.VERIFICATION_CODE_ERROR.getCode(),
                    BizCodeEnum.VERIFICATION_CODE_ERROR.getMsg());
        }

        //验证用户名密码是否正确  非加密形式验证用户名密码是否正确
        // AdminEntity admin = adminService.query()
        //         .eq("member_name", form.getMemberName())
        //         .eq("member_pass", form.getMemberPass())
        //         .one();

        //加密形式验证用户名密码是否正确
        AdminEntity admin = adminService.queryByUserName(form.getMemberName());

            //验证用户权限
            if(admin.getRole()!=1&&admin.getRole()!=2){
                return R.error(BizCodeEnum.USER_NOT_ADMIN.getCode(),BizCodeEnum.USER_NOT_ADMIN.getMsg());
            }

        // System.out.println(admin);
        //admin不存在或密码不正确
        if (admin == null || !admin.getMemberPass().equals(
                new Sha256Hash(form.getMemberPass(),admin.getSalt()).toHex())
        ){
            // System.out.println("进入方法");
            // System.out.println(admin.getMemberPass());
            // System.out.println(new Sha256Hash(form.getMemberPass(),admin.getSalt()).toHex());
            return R.error(BizCodeEnum.USERNAME_OR_PASSWORD_ERROR.getCode(),
                    BizCodeEnum.USERNAME_OR_PASSWORD_ERROR.getMsg());
        }

        return R.ok().put("data", "welcome to system");
    }

    /**
     * 保存
     */
    @RequestMapping(value = "/save")
    @Operation(summary ="添加用户")
    //@RequiresPermissions("payment:admin:save")
    public R save(@Validated({AddGroup.class}) @RequestBody AdminEntity admin){
        boolean b = adminService.saveUser(admin);
        if(!b){
            return R.error(BizCodeEnum.USER_EXIST.getCode(),
                    BizCodeEnum.USER_EXIST.getMsg());
        }
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @Operation(summary ="修改用户")
    //@RequiresPermissions("payment:admin:update")
    public R update(@Validated({UpdateGroup.class}) @RequestBody AdminEntity admin){
        // System.out.println(admin);
        boolean b = adminService.updateUser(admin);
        if(!b){
            return R.error(BizCodeEnum.PASSWORD_VALID_ERROR.getCode()
                    ,BizCodeEnum.PASSWORD_VALID_ERROR.getMsg());
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @Operation(summary ="删除用户")
    //@RequiresPermissions("payment:admin:delete")
    public R delete(@RequestBody Integer[] ids){
        // System.out.println(Arrays.asList(ids).toString());
		adminService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }
}
